var path = require("path")
	,	HOME = process.env.HOME || process.env.USERPROFILE
	, aws	 = require("aws-lib")
	, config = require(path.join(HOME, '.aws', 'config.json'))
	, prodAdv = aws.createProdAdvClient(config.accessKeyId, config.secretAccessKey, config.associateTag)
	,	sdb = aws.createSimpleDBClient(config.accessKeyId, config.secretAccessKey,{secure:false})


exports.Select = function(query, callback) {
	// expression
	var arrExpr = [];

	if(!!query.expr) {
		Object.keys(query.expr).forEach(function(k){
			// filter keys whose value is empty
			if (this[k]) arrExpr.push([k, "=", "'", this[k], "'"].join(""));
		}, query.expr);
	}

	var select = ["select * from", query.domain_name];

	if (arrExpr.length > 0) {	// append expression
		select.push("where");
		select.push(arrExpr.join(" and "));
	}

	if (!!query.limit) {	// append page size
		select.push("limit");
		select.push(query.limit);
	}

	var q = select.join(" ");
	//console.log(q);
	// TODO support NextToken for pagination
	sdb.call("Select", {SelectExpression:q}, callback);
}

// lookup item via ASIN
exports.ItemLookup = function(ASIN, callback) {
	prodAdv.call("ItemLookup", {ItemId: ASIN, IdType: "ASIN"}, callback);
}

// list all simpleDB
exports.ListDomains = function(callback) {
	sdb.call("ListDomains", {}, callback);
}
